package com.atguigu.gulimall.order.controller;

import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.entity.OrderReturnReasonEntity;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.annotation.RabbitListeners;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@RabbitListener(queues = {"hello-java-queue"})
@RestController
public class RabbitController {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @GetMapping("/sendMessage")
    public String sendMessage(@RequestParam("num") Integer num) {
        //退款原因
        OrderReturnReasonEntity returnReason = new OrderReturnReasonEntity();

        //订单
        OrderEntity orderEntity = new OrderEntity();


        //发送几次消息
        for (int i = 0; i < num; i++) {
            if (i % 2 == 0) {
                returnReason.setName("退款:" + i + 1);
                returnReason.setId(i + 1L);
                rabbitTemplate.convertAndSend("hello-java-exchange", "hello.java", returnReason, new CorrelationData(UUID.randomUUID().toString()));
            } else {
                orderEntity.setId(i + 1L);
                orderEntity.setOrderSn(UUID.randomUUID().toString());
                rabbitTemplate.convertAndSend("hello-java-exchange", "hello.java", orderEntity, new CorrelationData(UUID.randomUUID().toString()));
            }
        }
        return "sendSuccess";
    }

    @RabbitHandler
    public void receiveMessage(Message message, Channel channel, OrderReturnReasonEntity orderReturnReasonEntity) throws Exception {
        //消息的标识
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        //channel内的消息deliverTag是递增的
        //void basicAck(long deliveryTag, boolean multiple) throws IOException; multiple:是否批量确认
        if (deliveryTag % 2 == 0) {
            channel.basicAck(deliveryTag, false);
            System.out.println("接收到的消息orderReturnReasonEntity:" + orderReturnReasonEntity);
        } else {
            //void basicNack(long deliveryTag, boolean multiple, boolean requeue)  :是否重新入队
            channel.basicNack(deliveryTag, false, false);
        }
    }

    @RabbitHandler
    public void receiveMessage2(OrderEntity orderEntity) {
        System.out.println("接收到的消息orderEntity:" + orderEntity);
    }

}
